

library(ggplot2)

theme_new <- function(base_size = 16, base_family = "Helvetica"){
  theme_bw(base_size = base_size, base_family = base_family) %+replace%
    theme(
      panel.grid = element_blank(),   
      panel.border = element_rect(fill = NA, colour = "gray", size=1),
      panel.background = element_rect(fill = "white", colour = "black"), 
      strip.background = element_rect(fill = NA),
      axis.text.x = element_text(color = "black"),
      axis.text.y = element_text(color = "black")
    )
}

## weighted prop./ordering function
weighted_prop_summaries <- function(df, grouping_var, name_toassign){
  
  summary_groups <- df %>%
    group_by(!!sym(grouping_var)) %>%
    summarise(count = sum(derived_comb_weight),
              prop = count/sum(df$derived_comb_weight)) %>%
    ungroup() %>%
    mutate(dem = name_toassign) %>%
    rename(level = !!sym(grouping_var)) %>%
    mutate(level = reorder(level, prop))
  
  return(summary_groups)
  
}

## bivar for likert dvs
weighted_prop_summary_bivar <- function(df, grouping_var,
                                        dv_var,
                                        name_dv){
  
  summary_groups <- df %>%
    group_by(!!sym(grouping_var), !!sym(dv_var)) %>%
    summarise(num = sum(derived_comb_weight)) %>%
    ungroup() %>%
    left_join(df %>% group_by(!!sym(grouping_var)) %>%
                summarise(denom = sum(derived_comb_weight)) %>%
                ungroup()) %>%
    mutate(prop = num/denom,
           cat_forgraph = factor(!!sym(dv_var),
                                 levels = order_likert,
                                 ordered = TRUE),
           name_dv = name_dv) %>%
    dplyr::select(-dv_var)
  
  return(summary_groups)
  
}

## functions for weighted inference
## run separately for each status quo condition
compare_statusquo_alg_binary <- function(one_statusquo, full_data){
  
  ## subset to that condition to get correct denom
  df_compare = full_data %>% filter(derived_statusquo_cond == one_statusquo)
  
  ## generate weighted counts to feed prop.test
  count_alg <- sum(df_compare$derived_comb_weight[df_compare$derived_alg_morefair])
  count_total <- sum(df_compare$derived_comb_weight)
  count_other <- count_total - count_alg
  
  test_result = prop.test(c(count_alg, count_other), 
                          c(count_total, count_total),
                          alternative = "two.sided")
  return(test_result)
  
}


process_proptest <- function(one_result){
  
  df <- data.frame(alg_morefair = one_result$estimate["prop 1"],
                   other_morefair = one_result$estimate["prop 2"],
                   p = one_result$p.value)
  
  return(df)
  
}

## for ordered factors, distinc levels
educ_levels <- c("HS or less",
                 "Some college",
                 "College or\nprofessional school")
polideo_levels <- c("Slightly - extremely conservative",
                    "Moderate",
                    "Slightly - extremely liberal")


#' Complete list of palettes
#'
#' Use \code{\link{wes_palette}} to construct palettes of desired length.
#'
#' Color palettes were obtained from various websites include:
#' https://personal.sron.nl/~pault/#sec:qualitative
#' https://davidmathlogic.com/colorblind/#%23648FFF-%23785EF0-%23DC267F-%23FE6100-%23FFB000
#' https://bookdown.org/hneth/ds4psy/ds4psy_files/figure-html/apx-color-define-rgb-1.png
#'
#' @export
friendly_pals <- list(
  bright_seven = c("#4477AA", "#228833", "#AA3377", "#BBBBBB", "#66CCEE", "#CCBB44", "#EE6677"),
  contrast_three = c("#004488", "#BB5566", "#DDAA33"),
  vibrant_seven = c("#0077BB", "#EE7733", "#33BBEE", "#CC3311", "#009988", "#EE3377", "#BBBBBB"),
  muted_nine = c("#332288", "#117733", "#CC6677", "#88CCEE", "#999933", "#882255", "#44AA99", "#DDCC77", "#AA4499"),
  nickel_five = c("#648FFF", "#FE6100", "#785EF0", "#FFB000", "#DC267F"),
  ito_seven = c("#0072B2", "#D55E00", "#009E73", "#CC79A7", "#56B4E9", "#E69F00", "#F0E442"),
  ibm_five = c("#648FFF", "#785EF0", "#DC267F", "#FE6100", "#FFB000"),
  wong_eight = c("#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7", "#000000"),
  tol_eight = c("#332288", "#117733", "#44AA99", "#88CCEE", "#DDCC77", "#CC6677", "#AA4499", "#882255"),
  zesty_four = c("#F5793A", "#A95AA1", "#85C0F9", "#0F2080"),
  retro_four = c("#601A4A", "#EE442F", "#63ACBE", "#F9F4EC")
)

#' A color blind friendly color palette generator
#'
#' Code is based on the wes anderson package https://github.com/karthik/wesanderson
#' These are a handful of color palettes that are color blind friendly.
#'
#' @param n Number of colors desired.
#' @param name Name of desired palette. Choices are:
#'   \code{bright_seven}, \code{contrast_three},  \code{vibrant_seven},
#'   \code{muted_nine}, \code{nickel_five},  \code{ito_eight}
#' @param type Either "continuous" or "discrete". Use continuous if you want
#'   to automatically interpolate between colours.
#'   @importFrom graphics rgb rect par image text
#' @return A vector of colours.
#' @export
#' @keywords colors
#' @examples

#'
#' # If you need more colours than normally found in a palette, you
#' # can use a continuous palette to interpolate between existing
#' # colours
#' pal <- friendly_pal(21, name = "muted_nine", type = "continuous")
#' image(volcano, col = pal)
friendly_pal <- function(name, n, type = c("discrete", "continuous")) {
  type <- match.arg(type)
  
  pal <- friendly_pals[[name]]
  if (is.null(pal))
    stop("Palette not found.")
  
  if (missing(n)) {
    n <- length(pal)
  }
  
  if (type == "discrete" && n > length(pal)) {
    stop("Number of requested colors greater than what palette can offer")
  }
  
  out <- switch(type,
                continuous = grDevices::colorRampPalette(pal)(n),
                discrete = pal[1:n]
  )
  structure(out, class = "palette", name = name)
}